package com.realbrand.net.realbrandpay.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.Static;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/12.
 */

public class SetPersonImageActivity extends BaseActivity {
    @BindView(R.id.setPersonImage_toolbar)
    Toolbar setPersonImageToolbar;
    @BindView(R.id.setPersonImage_iv_setImage)
    ImageView setPersonImageIvSetImage;
    private TextView popwindowPhotoAlbum, popwindowTakePhoto, popwindowAbolish, popwindowSavePhoto;
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESIZE_REQUEST_CODE = 2;
    private static final String IMAGE_FILE_NAME = "header.jpg";

    private PopupWindow popupWindow;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        setPersonImageToolbar.setTitle("");
        setPersonImageToolbar.setNavigationIcon(R.drawable.ic_back);
        setSupportActionBar(setPersonImageToolbar);
        setPersonImageToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        setOnClick();
        String urlPhoto = getIntent().getStringExtra("urlPhoto");
        Picasso.with(this).load(HTTPAPI.PHOTO_BASEURL + urlPhoto).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(setPersonImageIvSetImage);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.setimage_activity;
    }

    @Override
    protected void setOnClick() {
        setPersonImageIvSetImage.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击弹出弹窗选择是从相册选择照片还是拍照
            case R.id.setPersonImage_iv_setImage:
                if (popupWindow == null) {
                    View inflate = LayoutInflater.from(this).inflate(R.layout.popwindow_layout, null);
                    popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    //设置点击空白处让popuoWindow消失:设置四周可触摸
                    popupWindow.setOutsideTouchable(true);
                    //设置popupwindow从屏幕底部弹出
                    popupWindow.showAtLocation(SetPersonImageActivity.this.findViewById(R.id.setPersonImage), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    //设置popwindow布局子View的点击事件
                    setPopupWindowOnClick(inflate);
                } else {
                    if (popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    } else {
                        popupWindow.showAtLocation(SetPersonImageActivity.this.findViewById(R.id.setPersonImage), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    }
                }
                break;
        }
    }

    private void setPopupWindowOnClick(View view) {
        popwindowAbolish = (TextView) view.findViewById(R.id.popwindow_abolish);
        popwindowPhotoAlbum = (TextView) view.findViewById(R.id.popwindow_photoAlbum);
        popwindowTakePhoto = (TextView) view.findViewById(R.id.popwindow_takePhoto);
        popwindowSavePhoto = (TextView) view.findViewById(R.id.popwindow_savePhoto);
        //选择相册
        popwindowPhotoAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
//                galleryIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_REQUEST_CODE);
            }
        });
        //选择拍照
        popwindowTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSdcardExisting()) {
                    Intent cameraIntent = new Intent(
                            MediaStore.ACTION_IMAGE_CAPTURE);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
                    startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                } else {
                    Toast.makeText(v.getContext(), "请插入sd卡", Toast.LENGTH_LONG)
                            .show();
                }
            }
        });
        //取消
        popwindowAbolish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //保存图片
        popwindowSavePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击把图片传到设置个人信息界面
                Drawable drawable = setPersonImageIvSetImage.getDrawable();
                if (drawable == null) {
                    Static.toast(SetPersonImageActivity.this, "请选择上传图片");
                } else {
                    Bitmap bitmap = Static.drawableToBitmap(drawable);
                    Intent intent = new Intent();
                    intent.putExtra("bitmap", bitmap);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    resizeImage(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if (isSdcardExisting()) {
                        resizeImage(getImageUri());
                    } else {
                        Toast.makeText(SetPersonImageActivity.this, "未找到存储卡，无法存储照片！",
                                Toast.LENGTH_LONG).show();
                    }
                    break;
                case RESIZE_REQUEST_CODE:
                    if (data != null) {
                        showResizeImage(data);
                    }
                    break;
            }
        }
    }

    private boolean isSdcardExisting() {
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private void showResizeImage(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            setPersonImageIvSetImage.setImageDrawable(drawable);
        }
    }


    private Uri getImageUri() {

        return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME));
    }

    public void resizeImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }
}
